<?php
require_once './Unireset/Unirest.php';		// 引入Unirest 用于HTTP请求
class device extends CI_Controller {
	/**
		获取当前用户的设备列表
		如果有搜索关键字,则按关键字查询	
	*/ 
	public function __construct(){
		parent::__construct(); //必须初始化！！！！！！
		$this->config->load("user");
		$this->key = $this->config->item('key');
		$this->auth_url = $this->config->item('auth_url');
	}
	//获取设备列表,接口传入参数 keywords pageid
	//pageid 必须 keywords可空
	public function getDeviceList(){
		if($this->input->get("keywords")){
			$keywords = $this->input->get("keywords");
			$where = array(
				'start' => $this->input->get("pageid"),
				'like' => array(
					'ip' => $keywords,
					'comment' => $keywords,
					'task' => $keywords
				)
			);
			$res = $this->device->get_device_where($where);
			print_r(json_encode($res));
			
		}else{//否者直接取出数据
			$where = array(
				"start" => $this->input->get("pageid")
			);
			$res = $this->device->get_device_list($where);
			//echo $this->db->last_query();
			print_r(json_encode($res));
		}
	}
	/**
		扫描设置局域网段内的设备信息
		存在则添加
		不存在返回错误信息
	*/
	public function scanDevice(){
		$ip = $this->input->get("ip"); //ajax传入的设备IP
		if($this->ssh->init(array("ip" => $ip)) == "1"){
			$data = array(
				"ip" => $ip
			);
			$res = $this->device->add_device($data);
			print_r(json_encode($res));
			
		}elseif($this->ssh->init(array("ip" => $ip)) == "2"){
			print(json_encode(array(
				"ip" => $ip,
				"status" => "faild",
				"reason" => "设备用户名或密码错误"
			)));
		}elseif($this->ssh->init(array("ip" => $ip)) == "3"){
			print(json_encode(array(
				"ip" => $ip,
				"status" => "faild",
				"reason" => "端口未开放"
			)));
		}
	}
	
	public function ping(){
		$ip = $this->input->get("ip");
		exec("ping $ip -n 1",$info);  
		//获取ping的时间  
		$str = $info[count($info)-1];  
		echo intval(substr($str,strripos($str,'=')+1));
	}
	
	/**
		修改备注
	*/
	public function update_ramark(){
		$data = array(
			"id" => $this->input->get("id"),
			"comment" => $this->input->get("remark")
		);
		$this->device->update_ramark($data);
	}
	
	/**
		修改当前任务
		task=主线 task当前执行的操作
		http://127.0.0.1/CloudFlag-IOS/index.php/device/update_progress?ip=192.168.199.109&task=主线
	*/
	public function update_task(){
		$body = array(
			"ip" => $this->input->get("ip"),
			"task" => $this->input->get("task")
		);
		$res = $this->device->update_task($body);
		if($res){
			print_r(json_encode(array(
				"status" => "success"
			)));
		}else{
			print_r(json_encode(array(
				"status" => "failed"
			)));
		}
	}
	
	/**
		修改进度
		progress=1/10 比如说你的脚步进度有10个 前面是执行到第几个后面是一共多少个
		http://127.0.0.1/CloudFlag-IOS/index.php/device/update_progress?ip=192.168.199.109&progress=1/10
	*/
	public function update_progress(){
		$body = array(
			"ip" => $this->input->get("ip"),
			"progress" => $this->input->get("progress")
		);
		$res = $this->device->update_progress($body);
		if($res){
			print_r(json_encode(array(
				"status" => "success"
			)));
		}else{
			print_r(json_encode(array(
				"status" => "failed"
			)));
		}
	}
	/**
		设备重启
	*/
	public function device_reboot(){
		$ip = $this->input->get('ip');		// 获取ip
		$id = $this->input->get('id');		// 获取id
		if($this->ssh->init(array("ip" => $ip)) == "1"){
			$this->ssh->reboot();	// 调用重启方法
			
			
			print(json_encode(array(
				"status" => "success",
				"reason" => "设备重启成功"
			)));
		}elseif($this->ssh->init(array("ip" => $ip)) == "2"){
			print(json_encode(array(
				"status" => "faild",
				"reason" => "设备用户名或密码错误"
			)));
		}elseif($this->ssh->init(array("ip" => $ip)) == "3"){
			print(json_encode(array(
				"status" => "faild",
				"reason" => "设备端口未开放"
			)));
		}		
	}
	//获取ipa目录下的文件列表 并且输出json数据
	public function getipaslist(){
		$dir = dir("ipa");
		$i = 0;
		$o = 0;
		if($dir){
			while (($file = $dir->read()) !== false){
				$i++;
				if($i > 2){
					$o++;
					$files[$o] = $file;
				}
			}
			$dir->close();
			print(json_encode(array(
				'status' => 'success',
				'filelist' => $files
			)));
		}else{
			print(json_encode(array(
				'status' => 'faild',
				'reason' => '目录不存在'
			)));
		}
		
	}
	
	//获取lua目录下的文件列表 并且输出json数据
	public function getluaslist(){
		$dir = dir("lua");
		$i = 0;
		$o = 0;
		if($dir){
			while (($file = $dir->read()) !== false){
				$i++;
				if($i > 2){
					$o++;
					$files[$o] = $file;
				}
			}
			$dir->close();
			print(json_encode(array(
				'status' => 'success',
				'filelist' => $files
			)));
		}else{
			print(json_encode(array(
				'status' => 'faild',
				'reason' => '目录不存在'
			)));
		}
		
	}
	
	//本段代码盲打 没有经过任何测试 测试后再用 2015年11月13日01:54:25
	
	/**
		命令安装ipa应用包
	*/
	public function ipainstaller(){		
		$auth = array(
			'ip' => $this->input->get('ip')
		);
		if($this->ssh->init($auth) != "1"){
			print(json_encode(array(
				'status' => 'faild',
				'reason' => '与设备连接失败'
			)));
		}else{
			
			// 判断手机上是否存在CloudFlat_logs文件夹
			$str = $this->ssh->exec_Ret('ls');
			if(!strstr($str,"CloudFlat_logs")){
				// 不存在则创建
				$this->ssh->exec_Ret("mkdir CloudFlat_logs");
			}
			
			// 判断手机上是否存在要安装的ipa
			if(strstr($str,$this->input->get('ipa_file_name'))){
				$this->ssh->exec_Ret("rm {$this->input->get('ipa_file_name')}");	// 有则删除
			}else{
				$this->ssh->exec("wget {$this->config->item('local_url')}/ipa/{$this->input->get('ipa_file_name')} && ipainstaller {$this->input->get('ipa_file_name')}");

				print(json_encode(array(
					'status' => 'success',
					'reason' => '命令执行成功,具体安装情况请查看手机',
				)));
			}
		}		
	}
	 
	/**
		向设备发送脚本
		1.向当前用户下的所用设备发送脚本
		2.根据关键字查询后向设备发送脚本
	*/
	public function sendlua(){
		$auth = array(
			'ip' => $this->input->get('ip')
		);
		if($this->ssh->init($auth) != "1"){
			print(json_encode(array(
				'ip' => $this->input->get('ip'),
				'status' => 'faild',
				'reason' => '与设备连接失败'
			)));
		}else{
			// 判断手机上是否存在touchelf文件夹
			$str = $this->ssh->exec_Ret('ls /var');
			if(!strstr($str,"touchelf")){
				// 不存在则提示安装触摸精灵
				print(json_encode(array(
					'status' => 'falid',
					'ip' => $this->input->get('ip'),
					'reason' => '未安装触摸精灵',
				)));
			}else{
				$luaarr = $this->ssh->getScriptList();	// 返回脚本数组
				if(in_array($this->input->get('file_name'),$luaarr)){
					$this->ssh->exec_Ret("rm /var/touchelf/scripts/{$this->input->get('file_name')}");	// 有则删除
					$this->ssh->rWget("{$this->config->item('local_url')}/lua/{$this->input->get('file_name')}","/var/touchelf/scripts/");
					
					
					print(json_encode(array(
						'status' => 'success',
						'ip' => $this->input->get('ip')
					)));
				}else{
					$this->ssh->rWget("{$this->config->item('local_url')}/lua/{$this->input->get('file_name')}","/var/touchelf/scripts/");
					
					
					print(json_encode(array(
						'status' => 'success',
						'ip' => $this->input->get('ip')
					)));
				}
			}
		}
	}
	
	/**
		启动脚本
		1.向当前用户下的所用设备启动脚本
		2.根据关键字查询后向启动脚本
	*/
	public function startscript(){
		// 发送给e的参数
		$parm = array(
			'ip' => '127.0.0.1',
			'port' => 19730,
			'data' => "{LUA}[{$this->input->get('ip')}]({$this->input->get('file_name')})"
		);
		// 连接设备的参数
		$auth = array(
			'ip' => $this->input->get('ip')
		);
		if($this->ssh->init($auth) != "1"){
			print(json_encode(array(
				'status' => 'faild',
				'reason' => '与设备连接失败'
			)));
		}else{
			$data = $this->socket_E($parm);
			print($data);
			if($data){
			}
		}
	}
	
	/**
		停止脚本
		1.向当前用户下的所用设备启动脚本
		2.根据关键字查询后向启动脚本
	*/
	public function stopscript(){
		// 发送给e的参数
		$parm = array(
			'ip' => '127.0.0.1',
			'port' => 19730,
			'data' => "{LUA}[{$this->input->get('ip')}]()"
		);
		// 连接设备的参数
		$auth = array(
			'ip' => $this->input->get('ip')
		);
		if($this->ssh->init($auth) != "1"){
			print(json_encode(array(
				'status' => 'faild',
				'reason' => '与设备连接失败'
			)));
		}else{
			$data = $this->socket_E($parm);
			print($data);
			if($data){
			}
		}
	}
	
	/**
		远程控制单台设备
	*/
	public function remote_control(){
		// 发送给e的参数
		$parm = array(
			'ip' => '127.0.0.1',
			'port' => 19730,
			'data' => "{VNC}[{$this->input->get('ip')}](5900)"
		);
		// 连接设备的参数
		$auth = array(
			'ip' => $this->input->get('ip')
		);
		if($this->ssh->init($auth) != "1"){
			print(json_encode(array(
				'status' => 'faild',
				'reason' => '与设备连接失败'
			)));
		}else{
			$data = $this->socket_E($parm);
			print($data);
			if($data){
			}
		}
	}
	
	private function socket_E($parm){
		error_reporting(E_ALL);  
		$service_port = $parm['port'];  
		$ip = $parm['ip'];  
		$data = $parm['data'];		
		$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); 
		if ($socket < 0) {  
			return json_encode(array(
				'status' => 'error',
				'reason' => socket_strerror($socket)
			));
		}
		$res = socket_connect($socket, $ip, $service_port);  
		if ($res < 0) {  
			return json_encode(array(
				'status' => 'error',
				'reason' => socket_strerror($res)
			));
		}
		socket_write($socket, $data, strlen($data));  
		while ($out = socket_read($socket, 2048)) {  
			return json_encode(array(
				'status' => 'success',
				'reason' => $out
			));
		}
		socket_close($socket);
	}
}